%% CREATE DATASEGMENTS
% *** User parameters
preTrigMs=[200 200 200 200 200 200 200 200 1000 1000 1000]; 
postTrigMs=[1500 1500 1500 1500 1500 1500 1500 1500 1500 1500 1500];
triggers2Include={[1],[2],[3],[4],[5],[6],[7],[1:7],[8],[16],[8 16]}; % Can be lists of trigger e.g {[1 2], [5 6 7]] would create one set combining all segments around triggers 1 & 2 and a scond set around triggers 5 & 6 & 7   
%tagsForOutputfile=
%blockwiseCAR={}; %define her blocks of channels fo common mode rejection (e.g. CAR removal) 
nameOfEcogFileToLoad='ecog'; % the data file we work on
namesOfEcogFileForResults={'ecogRawStimulus1','ecogRawStimulus2','ecogRawStimulus3','ecogRawStimulus4','ecogRawStimulus5','ecogRawStimulus6','ecogRawStimulus7','ecogRawAllStimuli','ecogRawButtonPress1','ecogRawButtonPress2','ecogRawAllButtonPresses'}; % a characteristic tag for each of the triggers sets defined above; % the data file we write to. The 'tagsForOutputfile' will be  postpended.

%RUN THIS TO CREATE SEGMENTS
if length(triggers2Include) ~= length(namesOfEcogFileForResults)
    error(['Unequal number of elemnts: triggers2Include ' num2str(length(triggers2Include)) ' namesOfEcogFileForResults ' num2str(length(namesOfEcogFileForResults))]);
end
load(nameOfEcogFileToLoad)
ecogFull=ecog;
sampDur=ecog.sampDur;
for k=1:length(triggers2Include) %loops around trigger sets. Results of each loop are save to a different file.
    disp(['Now processing: ' namesOfEcogFileForResults{k}]); 
    triggerIdx=[];
    curTriggers=triggers2Include{k};
    for m=1:length(curTriggers)
        triggerIdx=[triggerIdx find(ecogFull.triggerTS==curTriggers(m))];
    end
    if ~isempty(triggerIdx)
        [ecog.data,bas]=ecogSegmentTS(ecogFull.data',triggerIdx,ceil(preTrigMs(k)/ecogFull.sampDur),ceil(postTrigMs(k)/ecogFull.sampDur));
        [ecog.triggerTS,bas]=ecogSegmentTS(ecogFull.triggerTS',triggerIdx,ceil(preTrigMs(k)/ecogFull.sampDur),ceil(postTrigMs(k)/ecogFull.sampDur));
        ecog.data=permute(ecog.data,[2 1 3]);
        ecog.timebase=[-ceil(preTrigMs(k)/ecogFull.sampDur)+1:ceil(postTrigMs(k)/ecogFull.sampDur)]*ecogFull.sampDur;
        ecog.triggerTS=permute(ecog.triggerTS,[2 1 3]);
        ecog.nSamp=length(ecog.timebase);
        save(namesOfEcogFileForResults{k},'-v7.3','ecog');
%         if blockwiseCAR
%             ecogRaw=ecog;
%             %ecog=ecogPCANoiseRemoval(ecogRaw);
%             %save(['ecogPCARemovedSegments' num2str(k)],'ecog');
%             %Blockwise CAR
%             ecogFinal=ecogRaw;
%             for nBlocks=1:4
%                 ecog.data=ecogRaw.data((nBlocks-1)*64+1:nBlocks*64,:);
%                 ecog=ecogRemoveCommonAverageReference(ecogRaw);
%                 ecogFinal.data((nBlocks-1)*64+1:nBlocks*64,:)=ecog.data;
%                 ecogFinal.refChanTS(nBlocks,:)=ecog.refChanTS;
%             end
%             ecog=ecogFinal;
%         else
%             ecog=ecogRemoveCommonAverageReference(ecogRaw);
%         end
%         save(['nameOfEcogFileForResults num2str(k)],'ecog');
    else
        disp(['No events for trigger: ' num2str(k)]);
    end
end

%% Check potential trigger overlaps in the single trials 
% A list of bad trials is stored in the field badTrials
% *** User parameters
nameOfEcogFilesToLoad={'ecogRawStimulus1','ecogRawStimulus2','ecogRawStimulus3','ecogRawStimulus4','ecogRawStimulus5','ecogRawStimulus6','ecogRawStimulus7','ecogRawAllStimuli','ecogRawButtonPress1','ecogRawButtonPress2','ecogRawAllButtonPresses'};
nameOfEcogFilesToSave=nameOfEcogFilesToLoad;

% RUN THIS
for k=1:length(nameOfEcogFilesToLoad)
    disp(['Now processing: ' nameOfEcogFilesToLoad{k}]);
    load(nameOfEcogFilesToLoad{k});
    figure
    badTrials=[];
    for m=1:size(ecog.data,3)
        plot(ecog.timebase,squeeze(ecog.triggerTS(1,:,m)));
        title(['trial: ' num2str(m)])
        flag = 0;
        while flag==0
            r=input(['Good trial? [y]/n '],'s');
            if strcmpi('y',r)
                flag = 1;
                % Next trial
            elseif strcmpi('n',r)
                badTrials=[badTrials k];
                flag=1;
            else
                disp('Inavlid answer. Try again.')
                flag=0;
            end
        end
    end
    ecog.badTrials=badTrials;
    disp('Wait saving results')
    save(nameOfEcogFilesToSave{k},'-v7.3','ecog')
end
